package example.service.impl;

import example.common.Result;
import example.dto.SecIdAndDepNameDTO;
import example.dto.SecondmentInfoDTO;
import example.entity.SecondmentContentInfo;
import example.entity.TaskList;
import example.entity.UserInfo;
import example.mapper.DepartmentMapper;
import example.mapper.SecondmentContentInfoMapper;
import example.mapper.TaskListMapper;
import example.mapper.UserInfoMapper;
import example.service.IUserInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private TaskListMapper taskListMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private SecondmentContentInfoMapper secondmentContentInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.save(userInfo);
    }

    @Override
    @Transactional
    public Result checkUserQualification(UserInfo userInfo) {
        try {
            //该人员所属部门
            String departmentName = userInfo.getDepartmentName();
            Long secondmentId = userInfo.getSecondmentId();
            SecIdAndDepNameDTO secIdAndDepNameDTO = new SecIdAndDepNameDTO();
            secIdAndDepNameDTO.setSecondmentId(secondmentId);
            secIdAndDepNameDTO.setDepartmentName(departmentName);

            // 一、同时段 一个单位借调的人员数不超过单位编制人数的 2% 小于等于
            // 借调数量
            Integer secondmentNumber = userInfo.getSecondmentNumber(); // 这是前端传过来的借调人数
            // 计算部门最大借调人数 以及已经借调出去过的人
            Integer employeeNumber = departmentMapper.getEmployeeNumber(departmentName);
            Integer maxNumber = (int) (employeeNumber * 1.0 * 0.02);
            Integer secondmentEdNumber = userInfoMapper.getState(departmentName);
            //计算还能借调多少人
            maxNumber -= secondmentEdNumber;
            if (secondmentNumber > maxNumber) {
                secIdAndDepNameDTO.setState("待处理");
                secIdAndDepNameDTO.setTips("资格校验自动备注：超出最大借调人数，请手动选择，可选择 " + (maxNumber>0?maxNumber:0 )+ " 人。");
                //将该借调事件该部门状态和备注修改
                secondmentContentInfoMapper.changeNumberProblemState(secIdAndDepNameDTO);
                return Result.ok("校验成功！");
            }

            // 二、我可以一条一条判断 只需要用户名称 或者用户id
            SecondmentInfoDTO secondmentInfoDTO = new SecondmentInfoDTO();
            secondmentInfoDTO.setSecondmentId(secondmentId);
            secondmentInfoDTO.setDepartmentName(departmentName);
            //该借调事件该部门的所有人
            List<SecondmentContentInfo> secondmentContentInfoList = secondmentContentInfoMapper.getAllBySecondmentId(secondmentInfoDTO);
            for (SecondmentContentInfo secondmentContentInfo : secondmentContentInfoList) {
                Long id = secondmentContentInfo.getId();
                String userId = secondmentContentInfo.getUserId();
                UserInfo user = userInfoMapper.getByUserId(userId);

                // 本 职级/衔级 借调次数不超过两次，注意是已借调的次数
                Integer jobTime = userInfoMapper.getJobTime(user);
                Integer partyTime = userInfoMapper.getPartyTime(user);

                if ((jobTime != null && jobTime >= 2) || (partyTime != null && partyTime >= 2)) {
                    //状态改为不同意，增加备注
                    secondmentContentInfoMapper.changeSameRankProblemState(id);
                    continue;
                }

                // 其中已经借调一次的 除同一任务外 两次借调间隔不少于一年
                List<TaskList> taskList = taskListMapper.countTime(userId);
                if (taskList.size() < 1) {
                    secondmentContentInfoMapper.changeGapYearTrueState(id);
                    continue;
                } else if (taskList.size() == 1) {
                    if (taskList.get(0).getSecondmentId().equals(userInfo.getSecondmentId())) continue;
                } else if (taskList.size() == 2) continue;
                TaskList task = taskList.get(0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                String endTime = sdf.format(task.getEndTime());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                LocalDate date = LocalDate.parse(endTime, formatter);
                //最近的借调事件一年以后的时间
                String oneYearLaterDate = date.plusYears(1).format(formatter);
                 //当前借调事件的借调时间
                String secondmentDate = secondmentContentInfo.getSecondmentDate();
                String secondmentLastTime = secondmentContentInfo.getSecondmentLastTime();
                String secondmentEndTime = toEndTime(secondmentDate, secondmentLastTime);
                Boolean gap = compareYear(oneYearLaterDate, secondmentEndTime);
                if (gap) {
                    secondmentContentInfoMapper.changeGapYearTrueState(id);
                } else {
                    secondmentContentInfoMapper.changeGapYearFalseState(id);
                }
            }
            return Result.ok("校验成功！");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("校验失败！");
        }
    }


    private String toEndTime(String currentDate, String lastTime) {
        int m = 0;
        for (int i = 0; i < lastTime.length(); i++) {
            char ch = lastTime.charAt(i);
            if (ch >= '0' && ch <= '9') {
                m = m * 10 + (ch - '0');
            }
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDate date = LocalDate.parse(currentDate, formatter);
        LocalDate date1 = date.plusMonths(m);
        return date1.format(formatter);
    }

    private Boolean compareYear(String year1, String year2) {
        int n  = year1.length();
        for (int i = 0; i < n; i++) {
            if (year1.charAt(i) < year2.charAt(i)) return true;
        }
        return false;
    }

    @Override
    public UserInfo get(UserInfo userInfo) {
        return userInfoMapper.getByUserId(userInfo.getUserId());
    }
}